package org.xm.controller;

import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpSession;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.xm.model.Result;
import org.xm.model.User;
import org.xm.service.UserService;

@RequestMapping("/user")
@Slf4j
@RestController
public class UserController {

    @Autowired
    private UserService userService;

    @PostMapping("/login")
    public Object login(String username, String password, HttpServletRequest request) {

        log.info("用户登录~");

        // 1. 判断用户输入信息是否正确
        User user = userService.selectUser(username);
        if (user == null || !user.getPassword().equals(password)) {
            log.info("账号或密码错误");
            return Result.error("账号或密码错误");
        }

        // 2. 登录成功后创建会话
        HttpSession session = request.getSession(true); // 为true代表创建会话
        log.info("创建session：{}", session);
        session.setAttribute("user", user);
        return Result.success("用户" + username + "登录成功");

    }

    @PostMapping("/register")
    public Result register(String username, String password) {

        log.info("用户注册~");
        User user = null;

        try {
            user = new User();
            user.setUserName(username);
            user.setPassword(password);
            int ret = userService.insertUser(user);
            // 通过对xml添加useGeneratedKeys="true" keyProperty="userId"，
            // 此时userId已被赋值
            log.info("注册成功, 用户：{}", user);
            return Result.success("用户id: " + user.getUserId());
        }
        catch (DuplicateKeyException e) {
            log.info("该用户名已被注册, {}", username);
            return Result.error("该用户名已被注册");
        }
    }

    @GetMapping("/getUserInfo")
    public Result getUserInfo(HttpServletRequest request) {
        log.info("获取登录用户信息");
        // 1. 先从请求中获取会话
        HttpSession session = request.getSession(false);
        if (session == null) {
            // 会话不存在，代表用户未登录
            log.info("用户未登录");
            return Result.error("用户未登录");
        }
        log.info("当前session为:{}", session);
        // 2. 从会话中获取存储的用户信息
        User user = (User) session.getAttribute("user");
        if (user == null) {
            log.info("获取不到用户对象");
            return Result.error("获取不到用户对象");
        }
        return Result.success(user);
    }
}
